import z from 'zod';
import { callDoubaoIntent } from './callDoubao';
import { greetingMarkdownList } from './greetingMessages';
import { registerToolToServer, toolMap } from './server';
import { call } from './ws';
export const logServer = (message: string, ...args: any[]) =>
  console.log(`[SERVER] ${message}`, ...args);

export const warnServer = (message: string, ...args: any[]) =>
  console.warn(`[SERVER] ${message}`, ...args);

export const errorServer = (message: string, ...args: any[]) =>
  console.error(`[SERVER] ${message}`, ...args);

export const registerTools = () => {
  // 注册 问好 工具
  registerToolToServer(
    'greeting',
    {
      title: 'hello master',
      description: 'hello master',
      inputSchema: { text: z.string() },
    },
    async ({ text }) => {
      const today = new Date();
      const weekday = today.getDay();
      const index = weekday === 0 ? 6 : weekday - 1; // 周日为第7条，其他正常偏移
      return {
        content: [
          {
            type: 'text',
            text: `hello master \n ${greetingMarkdownList[index]}`,
          },
        ],
      };
    }
  );
  // 注册 天气查询 工具
  registerToolToServer(
    'weather',
    {
      title: 'get_weather_by_city',
      description: '查询指定城市的当前天气信息（基于 wttr.in，无需 API key）',
      inputSchema: { city: z.string().describe('城市名称（支持中文或英文）') },
    },
    async ({ city }) => {
      const url = `https://wttr.in/${encodeURIComponent(city)}.png`;
      return {
        content: [
          {
            type: 'text',
            text: url,
          },
        ],
      };
    }
  );

  // 注册 QA 工具
  registerToolToServer(
    'qa',
    {
      title: 'Question Answering',
      description: 'Answer questions directly',
      inputSchema: { answer: z.string() },
    },
    async ({ answer }) => {
      const parts = `"${answer}".`.split(' ');
      return {
        content: parts.map((word) => ({ type: 'text', text: word + ' ' })),
      };
    }
  );
  // 注册 parse_intent 工具（自动调用其他工具）
  registerToolToServer(
    'parse_intent',
    {
      title: '意图解析器',
      description: '使用豆包识别用户意图并自动调用目标工具',
      inputSchema: { text: z.string(), sessionId: z.string() },
    },
    async ({ text, sessionId }, session) => {
      console.log('🚀 ~ registerTools ~ session:', session);
      logServer(`📥 接收到意图解析请求 sessionId: ${sessionId}`);
      logServer(`📥 接收到意图解析请求: ${text}`);
      if (!sessionId) throw new Error('未知工具');
      let reply = '';
      try {
        reply = await callDoubaoIntent(text, sessionId);
        logServer(`📤 豆包回复: ${reply}`);
      } catch (err: any) {
        errorServer(`❌ 调用豆包接口失败:`, err.response.data.error);
        return await toolMap['qa']({
          question: JSON.stringify(err.response.data.error),
          sessionId,
        });
      }

      try {
        const parsed = JSON.parse(reply);
        const tool = parsed.tool;
        const input = parsed.input;

        if (tool && input && toolMap[tool]) {
          logServer(`🔁 自动调用工具: ${tool}`, input);
          return await toolMap[tool]({ ...input, sessionId });
        } else {
          warnServer(`⚠️ 未识别的工具或缺失输入:`, parsed);
          throw new Error('未知工具');
        }
      } catch (e) {
        warnServer(`⚠️ 解析 JSON 失败或 fallback 到 QA`, e);
        return await toolMap['qa']({ question: reply, sessionId });
      }
    }
  );
  registerToolToServer(
    'changeTheme',
    {
      title: '改变页面的主题',
      description: '改变页面的主题',
      inputSchema: { theme: z.enum(['light', 'dark']).describe('主题类型'), sessionId: z.string() },
    },
    async ({ theme, sessionId }) => {
      if (!sessionId) return { content: [{ type: 'text', text: 'No sessionId' }] };
      const result = call(sessionId, 'changeTheme', { theme });

      let text = `${result.ok}`;
      if (result.text) {
        text += `: (${result.text})`;
      }
      return {
        content: [{ type: 'text', text: `主题已切换为: ${theme}` }],
      };
    }
  );
  registerToolToServer(
    'changeBackground',
    {
      title: '切换背景色',
      description: '切换页面背景颜色',
      inputSchema: {
        color: z.string().describe('背景颜色，支持颜色名称或十六进制值'),
        sessionId: z.string(),
      },
    },
    async ({ color, sessionId }) => {
      if (!sessionId) return { content: [{ type: 'text', text: 'No sessionId' }] };
      const result = call(sessionId, 'changeBackground', { color });

      let text = `${result.ok}`;
      if (result.text) {
        text += `: (${result.text})`;
      }
      return {
        content: [{ type: 'text', text: `背景颜色已修改为: ${color}` }],
      };
    }
  );
  //todo 前端需要适配
  registerToolToServer(
    'loadComponents',
    {
      title: '加载组件',
      description: '根据组件名称加载组件',
      inputSchema: {
        componentName: z
          .enum(['404', 'signIn', 'loading'])
          .describe('组件名称，支持 404、signIn、loading'),
        sessionId: z.string(),
      },
    },
    async ({ componentName, sessionId }) => {
      if (!sessionId) return { content: [{ type: 'text', text: 'No sessionId' }] };
      const result = call(sessionId, 'loadComponents', { componentName });

      let text = `${result.ok}`;
      if (result.text) {
        text += `: (${result.text})`;
      }
      return {
        content: [{ type: 'text', text: `已经加载组件: ${componentName}` }],
      };
    }
  );
};
